/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bpmlab.kivulifx.effects;

import javafx.event.EventHandler;
import javafx.scene.Camera;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.transform.Rotate;

/**
 *
 * @author bpmlab
 */
public class CameraEvent {

    private static final double fps = 25;

    private double mouseXold = 0;
    private double mouseYold = 0;
    private Rotate xRotate = new Rotate(0, 0, 0, 0, Rotate.X_AXIS);
    private Rotate yRotate = new Rotate(0, 0, 0, 0, Rotate.Y_AXIS);
    private final double rotateModifier = 50;
    
    private final EventHandler<KeyEvent> move;
    private final EventHandler<MouseEvent> view;

    public CameraEvent(Camera camera) {
        move = (KeyEvent event) -> {
            KeyCode pressed = event.getCode();
            if (pressed == KeyCode.W) {
                camera.setTranslateZ(camera.getTranslateZ() + fps);
            } else if (pressed == KeyCode.S) {
                camera.setTranslateZ(camera.getTranslateZ() - fps);
            } else if (pressed == KeyCode.A) {
                camera.setTranslateX(camera.getTranslateX() - fps);
            } else if (pressed == KeyCode.D) {
                camera.setTranslateX(camera.getTranslateX() + fps);
            } else if (pressed == KeyCode.UP) {
                camera.setTranslateY(camera.getTranslateY() - fps);
            } else if (pressed == KeyCode.DOWN) {
                camera.setTranslateY(camera.getTranslateY() + fps);
            }
        };

        camera.getTransforms().addAll(xRotate, yRotate);
        view = event -> {
            if (event.getEventType() == MouseEvent.MOUSE_PRESSED
                    || event.getEventType() == MouseEvent.MOUSE_DRAGGED) {
                double mouseXnew = event.getSceneX();
                double mouseYnew = event.getSceneY();
                if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) {
                    double pitchRotate = xRotate.getAngle() + (mouseYnew - mouseYold) / rotateModifier;
                    xRotate.setAngle(pitchRotate);
                    double yawRotate = yRotate.getAngle() - (mouseXnew - mouseXold) / rotateModifier;
                    yRotate.setAngle(yawRotate);
                }
                mouseXold = mouseXnew;
                mouseYold = mouseYnew;
            }
        };
        
    }

    public EventHandler<KeyEvent> getMove() {
        return move;
    }

    public EventHandler<MouseEvent> getView() {
        return view;
    }

}
